package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import dao.CustomDao;
import entity.Custom;
import util.DBUtils;

public class CustomDaoImpl implements CustomDao {

	@Override
	public boolean insert(Custom c) {
		// try(){} 会把(定义的变量) try后执行con.close()帮我们关闭连接
		try(Connection con = DBUtils.getConnection()){
			String sql = "insert into custom(name,pwd,salt) values(?,?,?)";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setString(1, c.getName());
			ps.setString(2, c.getPwd());
			ps.setString(3, c.getSalt());
			int row = ps.executeUpdate();
			return row == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Custom selectByName(String name) {
		try(Connection con = DBUtils.getConnection()){
			String sql = "select * from custom where name=?";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setString(1, name);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				Custom c = new Custom();
				c.setId(rs.getInt(1));
				c.setName(name);
				c.setPwd(rs.getString(3));
				c.setSalt(rs.getString(4));
				return c;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean updateStat(Custom c, boolean b) {
		// try(){} 会把(定义的变量) try后执行con.close()帮我们关闭连接
		try(Connection con = DBUtils.getConnection()){
			String sql = "update custom set stat=? where id=?";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setBoolean(1, b);
			ps.setInt(2, c.getId());
			int row = ps.executeUpdate();
			return row == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
}
